package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"strconv"
	"taobao-merchandise/pkg"
	"taobao-merchandise/userrpc/userrpc"

	"taobao-merchandise/api/internal/svc"
	"taobao-merchandise/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("file")
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	fileType := req.FormValue("fileType")
	ext := filepath.Ext(m.Filename)
	switch fileType {
	case "1":
		if ext != ".png" && ext != ".jpg" {
			return &types.Response{
				Message: "图片上传类型仅支持png或jpg",
				Code:    500,
				Data:    nil,
			}, nil
		}
		if m.Size > 3*1024*1024 {
			return &types.Response{
				Message: "图片上传大小仅支持3M",
				Code:    500,
				Data:    nil,
			}, nil
		}
	case "2":
		if ext != ".txt" {
			return &types.Response{
				Message: "文件上传类型仅支持txt",
				Code:    500,
				Data:    nil,
			}, nil
		}
		if m.Size > 100*1024*1024 {
			return &types.Response{
				Message: "文件上传大小仅支持100M",
				Code:    500,
				Data:    nil,
			}, nil
		}
	case "3":
		if ext != ".mp4" {
			return &types.Response{
				Message: "视频上传类型仅支持mp4",
				Code:    500,
				Data:    nil,
			}, nil
		}
		if m.Size > 1000*1024*1024 {
			return &types.Response{
				Message: "视频上传大小仅支持1000M",
				Code:    500,
				Data:    nil,
			}, nil
		}
	}
	upload, err := pkg.Upload(file, m)
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	_, err = l.svcCtx.UserRpc.FileAdd(l.ctx, &userrpc.FileAddRequest{
		FileUrl:  upload,
		FileSize: strconv.FormatInt(m.Size, 10),
		FileType: fileType,
	})
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}

	return &types.Response{
		Message: "图片上传成功",
		Code:    200,
		Data:    upload,
	}, nil
}
